package com.wfh.wfhwx.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wfh.wfhwx.common.BaseResponse;
import com.wfh.wfhwx.common.ResultUtils;
import com.wfh.wfhwx.exception.BusinessException;
import com.wfh.wfhwx.exception.ErrorCode;
import com.wfh.wfhwx.exception.ThrowUtils;
import com.wfh.wfhwx.model.dto.WxAccountAddDto;
import com.wfh.wfhwx.model.dto.WxAccountPageQueryDto;
import com.wfh.wfhwx.model.dto.WxAccountUpdateDto;
import com.wfh.wfhwx.model.entity.User;
import com.wfh.wfhwx.model.entity.WxAccount;
import com.wfh.wfhwx.model.vo.WxAccountVO;
import com.wfh.wfhwx.service.UserService;
import com.wfh.wfhwx.service.WxAccountService;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author fenghuanwang
 */
@RestController
@RequestMapping("/wx/account")
public class WxAccountController {

    @Resource
    private UserService userService;

    @Resource
    private WxAccountService wxAccountService;

    private final WxMpService wxMpService = new WxMpServiceImpl();

    /**
     * 添加公众号
     * @param wxAccountAddDto
     * @param request
     * @return
     */
    @PostMapping("/add")
    @Operation(summary = "添加公众号")
    public BaseResponse<Long> addWxMpAccount(@RequestBody WxAccountAddDto wxAccountAddDto, HttpServletRequest request){
        // 参数校验
        if (ObjUtil.isEmpty(wxAccountAddDto)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 参数校验
        ThrowUtils.throwIf(StringUtils.isAnyBlank(wxAccountAddDto.getAppId(),
                wxAccountAddDto.getName(),
                wxAccountAddDto.getSecret(),
                wxAccountAddDto.getToken(),
                wxAccountAddDto.getAesKey()),ErrorCode.PARAMS_ERROR);
        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        Long res = wxAccountService.saveAndToRuntime(wxAccountAddDto, loginUser.getId());
        return ResultUtils.success(res);
    }

    /**
     * 删除公众号
     *
     * @param appIds
     * @return
     */
    @PostMapping("/del")
    public BaseResponse<Boolean> delWxMpAccount(@RequestBody List<String> appIds) {
        return ResultUtils.success(wxAccountService.delByAppIds(appIds));
    }

    /**
     * 更新公众号
     *
     * @param wxAccountUpdateDto
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateWxMpAccount(@RequestBody WxAccountUpdateDto wxAccountUpdateDto) {
        // 参数校验
        if (ObjUtil.isEmpty(wxAccountUpdateDto)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (StringUtils.isAnyBlank(wxAccountUpdateDto.getAppId())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "id不能为空");
        }
        return ResultUtils.success(wxAccountService.updateAndToRuntime(wxAccountUpdateDto));
    }

    /**
     * 分页查询公众号
     *
     * @param wxAccountPageQueryDto
     * @return
     */
    @GetMapping("/page")
    public BaseResponse<Page<WxAccountVO>> listWxMpAccountByPage(WxAccountPageQueryDto wxAccountPageQueryDto) {
        Page<WxAccount> wxAccountPage = wxAccountService.pageQuery(wxAccountPageQueryDto);
        List<WxAccountVO> collect = wxAccountPage.getRecords().stream()
                .map(wxAccount -> BeanUtil.copyProperties(wxAccount, WxAccountVO.class)).toList();
        Page<WxAccountVO> wxAccountVOPage = new Page<>();
        wxAccountVOPage.setRecords(collect);
        return ResultUtils.success(wxAccountVOPage);
    }

    /**
     * 查询公众号详情
     * @param appId
     * @return
     */
    @GetMapping("/access_token/get")
    @Operation(summary = "测试获取 access_token")
    public BaseResponse<String> getAccessToken(String appId) {
        try {
            wxMpService.switchover(appId);
            return ResultUtils.success(wxMpService.getAccessToken());
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, e.getMessage());
        }
    }

}

